package com.wcgksoft.controller.temp;


import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.entity.temp.KeyInformation;
import com.wcgksoft.entity.temp.Presentation;
import com.wcgksoft.entity.temp.ReportProblem;
import com.wcgksoft.entity.temp.Template;
import com.wcgksoft.service.tempservice.KeyInformationService;
import com.wcgksoft.service.tempservice.PresentationService;
import com.wcgksoft.service.tempservice.ReportProblemService;
import com.wcgksoft.service.tempservice.TemplateService;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Controller
@RequestMapping(value = "tempmanage")
public class TempManagController {

    @Autowired
    private KeyInformationService keyInformationService;

    @Autowired
    private PresentationService presentationService;

    @Autowired
    private ReportProblemService reportProblemService;


    @Autowired
    private TemplateService templateService;


    /**
     * 报告模板列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list")
    public Layui findAll(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "limit", required = false) Integer limit) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        DetachedCriteria criteria = DetachedCriteria.forClass(Presentation.class);
        criteria.add(Restrictions.eq("entid", sysUser.getEnterprise().getId()));
        List<Presentation> presentationList = presentationService.findByConditions(criteria, page, limit);
        return Layui.data(0, "查询成功", presentationService.getTotalCount(), presentationList);

    }


    /*
     * 报告添加/修改
     *
     * */
    @ResponseBody
    @RequestMapping(value = "update")
    public Layui update(@RequestParam(value = "b") String[] data,
                        @RequestParam(value = "n") String[] number,
                        @RequestParam(value = "tc") String[] tc,
                        @RequestParam(value = "file") MultipartFile[] f,
                        @RequestParam(value = "filenum") Integer[] filenum,
                        @RequestParam(value = "chk_value") Integer[] chk_value,
                        @RequestParam(value = "title") String title,
                        @RequestParam(value = "comiter") String comiter,
                        HttpServletRequest request,
                        @RequestParam(value = "t") String[] t) throws Exception {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        HashSet<Template> templates = new HashSet<>();
        if (null!=chk_value){
            for (Integer integer : chk_value) {
                Template byId = templateService.findById(integer);
                templates.add(byId);
            }
        }

//        System.out.println(chk_value.toString());
        System.out.println("标题"+title);
        System.out.println("报告者"+comiter);
        Presentation presentation = new Presentation();
        presentation.setEntid(sysUser.getEnterprise().getId());
        presentation.setComitetime(new Date());
        presentation.setTitle(title);
        presentation.setComiter(comiter);
        HashSet<KeyInformation> keyInformations = new HashSet<>();
        HashSet<ReportProblem> reportProblems = new HashSet<>();

        for (int i = 0; i < data.length; i++) {
            KeyInformation keyInformation = new KeyInformation();
            keyInformation.setTitle(data[i]);
            keyInformation.setContent(number[i]);
            keyInformationService.saveOrUpdate(keyInformation);
            keyInformations.add(keyInformation);
        }
        Integer s = 0;
        Integer m = 0;
        for (int i = 0; i < t.length; i++) {
            ReportProblem reportProblem = new ReportProblem();
            reportProblem.setTitle(t[i]);
            reportProblem.setContent(tc[i]);
            for (int i1 = s; i1 < s + filenum[i]; i1++) {
                m++;
                System.out.println(m);
                if (m==1){
                    try{
                        MultipartFile multipartFile = f[i1];
                        //得到文件"upload"的服务器路径
                        String sysPath=request.getSession().getServletContext().getRealPath("upload/picture");
                        String fileName=multipartFile.getOriginalFilename();    //得到文件名
                        File filePath=new File(sysPath,fileName);    //得到文件路径
                        if(!filePath.getParentFile().exists()){    //判断服务器当前路径文件夹是否存在
                            filePath.getParentFile().mkdirs();    //不存在则创建文件夹
                        }
                        //System.out.println("文件名"+fileName);

                        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filePath));
                        out.write(multipartFile.getBytes());
                        out.flush();
                        out.close();
                        reportProblem.setImage1("upload/picture/"+fileName);
                    }catch(Exception e){
                        System.out.println("上传失败"+e);
                    }
                }


                if (m==2){
                    try{
                        MultipartFile multipartFile = f[i1];
                        //得到文件"upload"的服务器路径
                        String sysPath=request.getSession().getServletContext().getRealPath("upload/picture");
                        String fileName=multipartFile.getOriginalFilename();    //得到文件名
                        File filePath=new File(sysPath,fileName);    //得到文件路径
                        if(!filePath.getParentFile().exists()){    //判断服务器当前路径文件夹是否存在
                            filePath.getParentFile().mkdirs();    //不存在则创建文件夹
                        }
                        //System.out.println("文件名"+fileName);

                        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filePath));
                        out.write(multipartFile.getBytes());
                        out.flush();
                        out.close();
                        reportProblem.setImage2("upload/picture/"+fileName);
                    }catch(Exception e){
                        System.out.println("上传失败"+e);
                    }
                }

                if (m==3){
                    try{
                        MultipartFile multipartFile = f[i1];
                        //得到文件"upload"的服务器路径
                        String sysPath=request.getSession().getServletContext().getRealPath("upload/picture");
                        String fileName=multipartFile.getOriginalFilename();    //得到文件名
                        File filePath=new File(sysPath,fileName);    //得到文件路径
                        if(!filePath.getParentFile().exists()){    //判断服务器当前路径文件夹是否存在
                            filePath.getParentFile().mkdirs();    //不存在则创建文件夹
                        }
                        //System.out.println("文件名"+fileName);

                        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filePath));
                        out.write(multipartFile.getBytes());
                        out.flush();
                        out.close();
                        reportProblem.setImage3("upload/picture/"+fileName);
                    }catch(Exception e){
                        System.out.println("上传失败"+e);
                    }
                }

                if (m==4){
                    try{
                        MultipartFile multipartFile = f[i1];
                        //得到文件"upload"的服务器路径
                        String sysPath=request.getSession().getServletContext().getRealPath("upload/picture");
                        String fileName=multipartFile.getOriginalFilename();    //得到文件名
                        File filePath=new File(sysPath,fileName);    //得到文件路径
                        if(!filePath.getParentFile().exists()){    //判断服务器当前路径文件夹是否存在
                            filePath.getParentFile().mkdirs();    //不存在则创建文件夹
                        }
                        //System.out.println("文件名"+fileName);

                        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filePath));
                        out.write(multipartFile.getBytes());
                        out.flush();
                        out.close();
                        reportProblem.setImage4("upload/picture/"+fileName);
                    }catch(Exception e){
                        System.out.println("上传失败"+e);
                    }
                }

                if (m==5){
                    try{
                        MultipartFile multipartFile = f[i1];
                        //得到文件"upload"的服务器路径
                        String sysPath=request.getSession().getServletContext().getRealPath("upload/picture");
                        String fileName=multipartFile.getOriginalFilename();    //得到文件名
                        File filePath=new File(sysPath,fileName);    //得到文件路径
                        if(!filePath.getParentFile().exists()){    //判断服务器当前路径文件夹是否存在
                            filePath.getParentFile().mkdirs();    //不存在则创建文件夹
                        }
                        //System.out.println("文件名"+fileName);

                        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(filePath));
                        out.write(multipartFile.getBytes());
                        out.flush();
                        out.close();
                        reportProblem.setImage5("upload/picture/"+fileName);
                    }catch(Exception e){
                        System.out.println("上传失败"+e);
                    }
                }


                // System.out.println(i1);
            }
            //System.out.println(s + "到" + (s + filenum[i]-1));
            s += (filenum[i]);
            //System.out.println("t"+t[i]);
            m=0;
            reportProblemService.saveOrUpdate(reportProblem);
            reportProblems.add(reportProblem);
        }

        presentation.setKeyInformationSet(keyInformations);
        presentation.setReportProblems(reportProblems);
        presentation.setTemplates(templates);
        presentationService.saveOrUpdate(presentation);
        return Layui.data(0, "更新成功", 1, null);

    }


    /**
     * 删除
     *
     * @param id
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    public Layui delete(@RequestParam(value = "id") String id) {
        Presentation presentation = presentationService.findById(id);
        presentationService.deleteCass(presentation);
        return Layui.data(1, "删除成功", 1, null);
    }


    /**
     * 将文件转成base64 字符串
     *
     * @param path文件路径
     * @return *
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }




    @RequestMapping("viow/{id}")
    public String viow(@PathVariable(value = "id")String id, ModelMap modelMap){
        System.out.println("查看页id"+id);
        Presentation byId = presentationService.findById(id);
        modelMap.put("viow", byId);
        return "repoment/viow";
    }

}
